
var dir = opera.io.filesystem.mountSystemDirectory('shared');
var app = opera.io.filesystem.mountSystemDirectory('application');

const MAIN_PAGE_NAME = 'MainPage';

function shareDirectory(dir, rootPath){
    dir.refresh();
    
    for (var i = 0, file; file = dir[i]; i++) {
        if (file.path[file.path.lastIndexOf('/') + 1] === '.') {
            continue;
        }
        if (file.isDirectory) {
            shareDirectory(file, rootPath);
        }
        else 
            if (file.isFile) {
                var path = file.path.slice(rootPath.length);
                opera.io.webserver.shareFile(file, file.path.replace(/^\/[^\/]+/, ''));
            }
    }
}

function shareStatic(dir){
    public_html = app.resolve('/' + dir + '/');
    shareDirectory(public_html, public_html.path);
};

window.onload = function(){
    webserver = opera.io.webserver
    
    shareStatic('css');
    shareStatic('js');
    
    if (webserver) {
        webserver.addEventListener('page', handleRequest, false);
        webserver.addEventListener('_index', handleIndex, false);
        webserver.addEventListener('save', handleSave, false);
        webserver.addEventListener('new', handleNew, false);
    }
}

function getPageNames() {
	var pageNames = new Array();
	dir.refresh();
	for (var i = 0; file = dir[i]; i++) {
		var pageName = dir[i].name;
        var index = pageName.lastIndexOf(".");
        pageName = pageName.substring(0, index);
		pageNames[pageName] = true;
	}
	return pageNames;
}

function populatePagesList(template){
    dir.refresh();
    var div = template.xpath("//div[@id='pagesList']")[0];
    for (var i = 0, file; file = dir[i]; i++) {
        var a = document.createElement("a");
        var fileName = dir[i].name;
        var index = fileName.lastIndexOf(".");
        fileName = fileName.substring(0, index);
        a.setAttribute("href", "{{_path}}page/" + fileName);
        a.appendChild(document.createTextNode(fileName));
        div.appendChild(a);
        div.appendChild(document.createElement("br"));
    }
}

function handleNew(e){
    var response = e.connection.response;
    var request = e.connection.request;
    
    var pageName = request.getItem('newPageName', 'POST')[0];
    
    createNewPage(pageName);
    var line = "";
    
    var data = {
        _path: "",
        _pageName: pageName,
        _pageText: ''
    };
    
    response.setStatusCode('301');
    response.setResponseHeader('Location', 'page/' + pageName);
    response.close();
}

function handleSave(e){
    var response = e.connection.response;
    var request = e.connection.request;
    
    var pageName = request.getItem('pageName', 'POST')[0];
    var text = request.getItem('text', 'POST')[0];
    text = unescape(text);
    
    writePageContent(pageName, text);
	text = readPageContent(pageName);
	
    var line = text.parseWiki();
    
    var data = {
        _path: "",
        _pageName: pageName,
        _pageText: text
    };
    
    response.setStatusCode('301');
    response.setResponseHeader('Location', 'page/' + pageName);
    response.close();
}

function handleIndex(e){

    var response = e.connection.response;
    
    createMainPageIfNotExist();
    
    var text = readPageContent(MAIN_PAGE_NAME);
    var line = text.parseWiki();        
    
    var data = {
        _path: '',
        _pageName: MAIN_PAGE_NAME,
        _pageText: text
    };
    
    var template = new Markuper('templates/index.html', data);
    populatePagesList(template);
    
    var div = template.xpath("//div[@id='tabs-1']")[0];
    div.innerHTML = line;
    
    response.write(template.parse().html());
    response.close();
    
}

function handleRequest(e){

    var request = e.connection.request;
    var response = e.connection.response;
    
    var uri = request.uri;
    
    var index = uri.lastIndexOf("/");
    var pageName = uri.substring(index + 1);
    
    var text = readPageContent(pageName);
    var line = text.parseWiki();
    
    
    var data = {
        _path: "../",
        _pageName: pageName,
        _pageText: text
    };
    var template = new Markuper('templates/index.html', data);
    populatePagesList(template);
    
    var div = template.xpath("//div[@id='tabs-1']")[0];
    div.innerHTML = line;
    
    response.write(template.parse().html());
    
    response.close();
    
}

function writePageContent(pageName, text){
    try {
        var file = dir.resolve('/shared/' + pageName + '.wiki');
        
        var stream = dir.open(file, opera.io.filemode.WRITE);
        stream.write(text);
        stream.close();
    } 
    catch (err) {
        opera.postError(err.message);
    }
}

function createNewPage(pageName){
    writePageContent(pageName, '');
}

function readPageContent(pageName){
    var file = dir.resolve('/shared/' + pageName + '.wiki');   
    
    var stream = dir.open(file, opera.io.filemode.READ);
    var wikiText = new Array();
    while (!stream.eof) {
        var line = stream.readLine();
        wikiText.push(line);
    }
    stream.close();
    return wikiText.join("\n");
}

function createMainPageIfNotExist() {
	var file = dir.resolve('/shared/' + MAIN_PAGE_NAME + '.wiki');
	if(!file.exists) {
		var mainPageTmpl = app.resolve('/wikitmpl/' + MAIN_PAGE_NAME + '.wiki');
		var streamIn = dir.open(mainPageTmpl, opera.io.filemode.READ);
				
		var streamOut = dir.open(file, opera.io.filemode.WRITE);
		
		while(!streamIn.eof) {
			streamOut.writeLine(streamIn.readLine());
		}
		
        streamIn.close();
        streamOut.close();
	}
}
